#include <stdio.h>
#include <time.h>
#include <sys/time.h>

/*os*/
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"

#include "nvs_flash.h"
#include "esp_log.h"

/*Init*/
#include "usart.h"
#include "Sntp.h"

/*APP*/
#include "trans.h"

const char *TAG = "sntp_stm";

static void bsp_init(void)
{
    usart_init(115200); // 调试串口初始化
    uart1_init(115200); // esp32和stm32之间的串口通信
    Sntp_init();        // sntp时钟初始化
}

void app_main(void)
{
    esp_err_t ret;
    ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES ||
        ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }

    /*data */
    char rec_stnp_buf[64];

    uint8_t hands_num = 0;
    const char hand_ack = 'B';
    /*funciton_init*/
    bsp_init();

    /*stm32和esp32之间进行握手,尝试连续三次握手*/
 hands:
    if (shake_hands()) {
        ESP_LOGI(TAG, "shake hands is sucessfully.");
        /*获取时间,并且发送给STM32*/
        get_stnp_info(rec_stnp_buf);
        //先发送BB，再发送后面的时间内容
        uart_write_bytes(UART_TRNAS_NUM, &hand_ack, 1);
        uart_write_bytes(UART_TRNAS_NUM, rec_stnp_buf, strlen(rec_stnp_buf));
    }else {
        hands_num++;
        if(hands_num == 3) {
            ESP_LOGI(TAG, "shake hands is error.");
        }
        else {
            goto hands;
        }
    }

    
    while (1)
    {
        ESP_LOGI(TAG, "main fuction is running");
        vTaskDelay(1000);
    }
}
